package com.wjc.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.CornerPathEffect;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.wjc.common.CommonExtKt;
import com.wjc.myktapplication.R;

/**
 * ClassName: com.wjc.basemodule.widget
 * Description:
 * JcChen on 2021.05.29.16:44
 */
public class ProgressWidget extends View {
    private static final String TAG = "ProgressWidget";
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    PathEffect pathEffect = new CornerPathEffect(getDpToPx(4));
    Path path = new Path();

    Paint.FontMetrics fontMetrics = new Paint.FontMetrics();

    private String keyCount = "130";

    float progressCircleRadius = getDpToPx(5);
    float progressStartX = getDpToPx(18);

    // 钥匙数显示
    float keyCountHeight = getDpToPx(13.5f);
    float keyCountWith = getDpToPx(24);
    float keyCountStartY = getDpToPx(23.5f);
    // 钥匙数显示的三角形
    float keyCountTipsWith = getDpToPx(10);
    float keyCountTipsHeight = getDpToPx(4);

    int KEY_LEVEL_COUNT = 5;

    int curKeyLevel = 0;

    int[] keyLevel = {0, 50, 200, 500, 1000, 2000};
    float[] keyLevelOpt = {50, 150, 300, 500, 1000, 1000};

    public ProgressWidget(Context context) {
        super(context);
        init();
    }

    public ProgressWidget(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ProgressWidget(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init() {
        setKeyCount("0");
    }


    @SuppressLint({"DrawAllocation", "UseCompatLoadingForDrawables"})
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setStyle(Paint.Style.FILL);
        // 整个进度条
        paint.setShader(null);
        paint.setColor(getResources().getColor(R.color.color_503A70));
        canvas.drawRoundRect(progressStartX, getProgressStartY(), getWidth() - getDpToPx(14),
                getProgressStartY() + progressCircleRadius, progressCircleRadius / 2, progressCircleRadius / 2, paint);
        drawKeyLevel(canvas);

        if (!"0".equals(keyCount)) { // 当前进度值与进度条
            drawCurKeyCount(canvas);
            paint.setShader(new LinearGradient(progressStartX, getProgressStartY(), getCurrentEndX(),
                    getProgressStartY() + progressCircleRadius, 0xffFF37AD, 0xffFFF47D, Shader.TileMode.CLAMP));
            canvas.drawRoundRect(progressStartX, getProgressStartY(), getCurrentEndX(),
                    getProgressStartY() + progressCircleRadius, progressCircleRadius / 2, progressCircleRadius / 2, paint);
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void drawKeyLevel(Canvas canvas) {
        Bitmap keyBitmap;
        paint.setShader(null);
        for (int i = 1; i <= KEY_LEVEL_COUNT; i++) {
            // 绘制 x阶
            if (curKeyLevel >= i) {
                paint.setColor(getResources().getColor(R.color.white));
                keyBitmap = ((BitmapDrawable) getResources().getDrawable(R.mipmap.ic_tt_box_key_select)).getBitmap();

            } else {
                paint.setColor(getResources().getColor(R.color.color_40_white));
                keyBitmap = ((BitmapDrawable) getResources().getDrawable(R.mipmap.ic_tt_box_key_normal)).getBitmap();
            }
            paint.setTextSize(getDpToPx(13));
            canvas.drawText(i + "阶", progressStartX + getProgressWith() / KEY_LEVEL_COUNT * i - getDpToPx(15), getDpToPx(19), paint);

            // 绘制钥匙图标与文字
            RectF dst = new RectF(progressStartX + getProgressWith() / KEY_LEVEL_COUNT * i - getDpToPx(15) - (keyLevel[i] + "").length() * getDpToPx(7f),
                    getProgressStartY() + progressCircleRadius + getDpToPx(9.5f),
                    progressStartX + getProgressWith() / KEY_LEVEL_COUNT * i - getDpToPx(3) - (keyLevel[i] + "").length() * getDpToPx(7f),
                    getProgressStartY() + progressCircleRadius + getDpToPx(22f));
            canvas.drawBitmap(keyBitmap, null, dst, paint);

            paint.setTextSize(getDpToPx(12));
            canvas.drawText(keyLevel[i] + "", progressStartX + getProgressWith() / KEY_LEVEL_COUNT * i - (keyLevel[i] + "").length() * getDpToPx(7f),
                    getProgressStartY() + progressCircleRadius + getDpToPx(21f), paint);
        }
    }

    float cutKeyCountTip = getDpToPx(3);

    private void drawCurKeyCount(Canvas canvas) {
        paint.setShader(null);
        paint.setColor(getResources().getColor(R.color.FF2F8B));
        path.reset();
        // 绘制矩形,因为 keyCountWith 根据文字宽度来算，不太准备，需要修正
        canvas.drawRoundRect(getCurrentEndX() - cutKeyCountTip - keyCountWith / 2 - getDpToPx(4), keyCountStartY,
                getCurrentEndX() - cutKeyCountTip + keyCountWith / 2, keyCountStartY + keyCountHeight, keyCountHeight / 2, keyCountHeight / 2, paint);


        // 绘制三角形
        path.moveTo(getCurrentEndX() - keyCountTipsWith, keyCountStartY + keyCountHeight - 2); // 起点
        path.rLineTo(keyCountTipsWith / 2, keyCountTipsHeight); // 斜向下
        path.rLineTo(keyCountTipsWith / 2, -keyCountTipsHeight);
        paint.setPathEffect(pathEffect);
        canvas.drawPath(path, paint);

        // 绘制文字
        paint.setPathEffect(null);
        paint.getFontMetrics(fontMetrics);
        paint.setColor(getResources().getColor(R.color.white));
        paint.setTextSize(getDpToPx(10));
        if (keyCount.length() > 2) {
            canvas.drawText(keyCount, getCurrentEndX() - cutKeyCountTip - keyCountWith / 2, keyCountStartY + keyCountHeight - getDpToPx(4), paint);
        } else {
            canvas.drawText(keyCount, getCurrentEndX()  - keyCountWith / 2 , keyCountStartY + keyCountHeight - getDpToPx(4), paint);
        }
    }

    /**
     * 当前进度条结尾的X坐标点
     * progressStartX 控制与左边的距离
     *
     * @return x
     */
    private float getCurrentEndX() {
        return getProgressWith() / KEY_LEVEL_COUNT * curKeyLevel +
                getProgressWith() / KEY_LEVEL_COUNT / keyLevelOpt[curKeyLevel] * (Integer.parseInt(keyCount) - keyLevel[curKeyLevel])
                + progressStartX + progressCircleRadius / 2;
    }

    /**
     * 进度条的总长度
     *
     * @return x
     */
    private float getProgressWith() {
        return (getWidth() - progressStartX - getDpToPx(18));
    }

    /**
     * 进度条开始的Y坐标点
     *
     * @return x
     */
    private float getProgressStartY() {
        return keyCountStartY + keyCountHeight + keyCountTipsHeight - 3;
    }

    /**
     * 设置当前钥匙数，也是进度条的当前进度
     *
     * @param keyCount 钥匙数
     */
    public void setKeyCount(String keyCount) {
        this.keyCount = keyCount;

        int key = Integer.parseInt(keyCount);
        if (key >= 2000) {
            curKeyLevel = 5;
            this.keyCount = "2000";  // 最大为2000
        } else if (key >= 1000) curKeyLevel = 4;
        else if (key >= 500) curKeyLevel = 3;
        else if (key >= 200) curKeyLevel = 2;
        else if (key >= 50) curKeyLevel = 1;
        else curKeyLevel = 0;
        if (keyCount.length() > 2) {  // 计算keyCount 宽度
            keyCountWith = this.keyCount.length() * getDpToPx(7f);
        } else {
            keyCountWith = getDpToPx(20);
        }
        invalidate();
    }

    private float getDpToPx(float dp) {
        return CommonExtKt.getDp(dp);
    }


}
